package com.dsg.service;

import com.dsg.entity.Permission;
import com.dsg.mappers.PermissionMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static java.util.stream.Collectors.toList;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 通过权限获取全部的左边的菜单
     * @return
     */
    @Override
    public List<Permission> findPermissionList() {
        List<Permission> list1 = permissionMapper.findPermissionPermId(null);
        List<Permission> result = list1.stream().map(permission -> {
            Subject subject = SecurityUtils.getSubject();
            if(subject.isPermitted(permission.getPermCode())){
                  List<Permission> list2 = permissionMapper.findPermissionPermId(permission.getId());
                  if(list2 != null){
                      for(Permission perm : list2){
                          if(subject.isPermitted(perm.getPermCode())){
                             permission.getChildren().add(perm);
                          }
                      }
                  }
               return permission;
            }
            return null;
        }).collect(toList());
        return result;
    }

    /**
     *通过员工获取不同的权限
     * @param username
     * @return
     */
    @Override
    public List<String> findPermCode(String username) {
        return permissionMapper.findPermCode(username);
    }
}
